<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\exception\ValidateException;

use app\common\model\{User, UserNews, UserMate, UserAlbum, Img, UserFollow, UserHelp, Comment, CommentLike};
use app\common\validate\{UserValidate, UserMateValidate, AlbumValidate, FollowValidate, HelpValidate, CommentValidate};

class UserController extends BaseController
{
    private $userModel;

    public function __construct(User $userModel)
    {
        parent::initialize();
        $this->userModel = $userModel;
    }

    /** 查询用户信息 */
    public function user_info()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        /** 查询用户信息 */
        $user_info = $this->userModel->getFind(['id' => $data['user_id']]);

        if($user_info['code'] != 'ok'){
            $this->error_back($user_info['msg']);
        }

        unset($user_info['data']['password']);

        $this->success_back('ok', $user_info['data']);
    }

    /** 完善资料 */
    public function set_news()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('set_news')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userNewsModel = new UserNews();

        /** 查询用户资料 */
        $user_news_info = $userNewsModel->getFind(['user_id' => $data['user_id']], 'id');

        if($user_news_info['code'] == 'ok'){
            $this->error_back('已经完善过资料了，请勿重复提交');
        }

        $user_data = [
            'id'       => $data['user_id'],
            'nickname' => $data['nickname'],
            'email'    => $data['email'],
        ];

        /** 修改用户信息 */
        $flag = $this->userModel->edit($user_data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        /** 年龄 */
        $data['age'] = howOld($data['birthday']);

        /** 新增用户资料 */
        $news_flag = $userNewsModel->add($data);

        if($news_flag['code'] != 'ok'){
            $this->error_back($news_flag['msg']);
        }

        $this->success_back('编辑成功');
    }

    /** 设置择偶要求 */
    public function set_mate()
    {
        $data = input('');

        try{
            validate(UserMateValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userMateModel = new UserMate();

        /** 新增择偶标准 */
        $news_flag = $userMateModel->add($data);

        if($news_flag['code'] != 'ok'){
            $this->error_back($news_flag['msg']);
        }

        $this->success_back('编辑成功');
    }

    /** 新增相册 */
    public function album_add()
    {
        $data = input('');

        try{
            validate(AlbumValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $albumModel = new UserAlbum();

        /** 新增相册 */
        $flag = $albumModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        if(isset($data['imgs']) && !empty($data['imgs'])){
            $imgModel = new Img();

            $img_arr = json_decode($data['imgs']);

            $img_add_arr = [];
            foreach($img_arr as $v){
                $img_add_info = [
                    'obj_id' => $flag['data'],
                    'img'    => $v,
                ];

                $img_add_arr[] = $img_add_info;
            }

            /** 批量新增图片 */
            $imgModel->addAll($img_add_arr);
        }

        $this->success_back('添加成功');
    }

    /** 相册列表 */
    public function album_list()
    {
        $data = input('');

        try{
            validate(AlbumValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $albumModel = new UserAlbum();

        /** 相册列表 */
        $list = $albumModel->getList(['user_id' => $data['user_id']], 1, $data['page'], $data['limit'], 'id, name, role, create_time', 'id DESC');

        if($list['code'] != 'ok'){
            $this->error_back($list['msg']);
        }

        $this->success_back('ok', $list['data']);
    }

    /** 相册详情 */
    public function album_show()
    {
        $data = input('');

        try{
            validate(AlbumValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $albumModel = new UserAlbum();
        $imgModel = new Img();

        /** 相册信息 */
        $info = $albumModel->getFind(['id' => $data['album_id']], 'id, name, role, create_time');

        if($info['code'] != 'ok'){
            $this->error_back($info['msg']);
        }

        $imgs_info = $imgModel->getList(['obj_id' => $data['album_id'], 'type' => 1], 0, 0, 0, 'id, img', 'create_time DESC');

        if($imgs_info['code'] != 'ok'){
            $imgs = [];
        }else{
            $imgs = $imgs_info['data'];
        }

        $info['data']['imgs'] = $imgs;

        $this->success_back('ok', $info['data']);
    }

    /** 编辑相册 */
    public function album_edit()
    {
        $data = input('');

        try{
            validate(AlbumValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $albumModel = new UserAlbum();

        $data['id'] = $data['album_id'];

        /** 修改相册信息 */
        $flag = $albumModel->edit($data, ['id', 'name', 'role']);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        if(isset($data['imgs']) && !empty($data['imgs'])){
            $imgModel = new Img();

            $img_arr = json_decode($data['imgs']);

            $img_add_arr = [];
            foreach($img_arr as $v){
                $img_add_info = [
                    'obj_id' => $data['id'],
                    'img'    => $v,
                ];

                $img_add_arr[] = $img_add_info;
            }

            /** 批量新增图片 */
            $imgModel->addAll($img_add_arr);
        }

        $this->success_back('编辑成功');
    }

    /** 删除相册 */
    public function album_del()
    {
        $data = input('');

        try{
            validate(AlbumValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        /** 删除相册 */
        $flag = UserAlbum::destroy($data['album_id']);

        if(!$flag){
            $this->error_back('删除失败');
        }

        /** 删除相册里面的图片 */
        Img::where(['obj_id' => $data['album_id'], 'type' => 1])->delete();

        $this->success_back('删除成功');
    }

    /** 删除相册图片 */
    public function img_del()
    {
        $data = input('');

        try{
            validate(AlbumValidate::class)->scene('show_img')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        /** 删除相册 */
        $flag = Img::destroy($data['img_id']);

        if(!$flag){
            $this->error_back('删除失败');
        }

        $this->success_back('删除成功');
    }

    /** 关注列表 */
    public function follow_list()
    {
        $data = input('');

        try{
            validate(FollowValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $followModel = new UserFollow();

        $field = 'u.id, u.nickname, u.head_img';
        $where[] = ['f.user_id', '=', $data['user_id']];

        if($data['type'] == 1){
            $where[] = ['u.is_tutor', '=', 1];
        }else{
            $where[] = ['u.is_audience', '=', 1];
        }

        $list = $followModel
            ->alias('f')
            ->join('user u', 'f.to_user_id = u.id')
            ->where($where)
            ->field($field)
            ->page((int)$data['page'], (int)$data['limit'])
            ->select();

        if($list->isEmpty()){
            $this->error_back('暂无数据~');
        }

        foreach($list as $v){
            if(!empty($v['head_img'])){
                $v['head_img'] = config('app.url') . $v['head_img'];
            }
        }

        $this->success_back('ok', $list);
    }

    /** 关注||取关 */
    public function set_follow()
    {
        $data = input('');

        try{
            validate(FollowValidate::class)->scene('set')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new User();
        $followModel = new UserFollow();

        $where = ['user_id' => $data['user_id'], 'to_user_id' => $data['to_user_id']];
        $info = $followModel->getFind($where);

        if($info['code'] != 'ok'){
            $flag = $followModel->add($data);
            $field = '关注';

            /** 粉丝数自增 */
            $userModel->setIncField(['id' => $data['user_id']], 'fans');
        }else{
            $flag = $followModel->del($where);
            $field = '取关';

            /** 粉丝数自减 */
            $userModel->setDecField(['id' => $data['user_id']], 'fans');
        }

        if($flag['code'] != 'ok'){
            $this->error_back($field . '失败');
        }

        $this->success_back($field . '成功');
    }

    /** 发布求助 */
    public function help_add()
    {
        $data = input('');

        try{
            validate(HelpValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $helpModel = new UserHelp();

        /** 订单号 */
        $data['order_no'] = getOrderNo('QZ');

        /** 新增求助 */
        $flag = $helpModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        if(isset($data['imgs']) && !empty($data['imgs'])){
            $imgModel = new Img();

            $img_arr = json_decode($data['imgs']);

            $img_add_arr = [];
            foreach($img_arr as $v){
                $img_add_info = [
                    'obj_id' => $flag['data'],
                    'type'   => 2,
                    'img'    => $v,
                ];

                $img_add_arr[] = $img_add_info;
            }

            /** 批量新增图片 */
            $imgModel->addAll($img_add_arr);
        }

        $this->success_back('发布成功');
    }

    /** 求助列表 */
    public function help_list()
    {
        $data = input('');

        try{
            validate(HelpValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new User();
        $imgModel  = new Img();
        $helpModel = new UserHelp();

        $where = [];

        if(isset($data['user_id']) && $data['user_id'] != 0){
            $where = ['user_id' => $data['user_id']];
        }

        $field = 'id, user_id, price, content, create_time';

        /** 查询求助列表 */
        $list = $helpModel->getList($where, 1, $data['page'], $data['limit'], $field, 'id DESC');

        if($list['code'] != 'ok'){
            $this->error_back($list['msg']);
        }

        foreach($list['data'] as $k => $v){
            $user_info = $userModel->getFind(['id' => $v['user_id']], 'nickname, head_img');

            if($user_info['code'] != 'ok'){
                unset($list['data'][$k]);
                continue;
            }

            $v['user_info'] = $user_info['data'];
            $imgs = $imgModel->getList(['obj_id' => $v['id'], 'type' => 2], 0, 0, 0, 'img')['data'];

            $v['imgs'] = array_column($imgs->toArray(), 'img');
        }

        $this->success_back('ok', $list['data']);
    }

    /** 求助详情 */
    public function help_show()
    {
        $data = input('');

        try{
            validate(HelpValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new User();
        $imgModel  = new Img();
        $helpModel = new UserHelp();

        $where = ['id' => $data['help_id']];

        $field = 'id, user_id, price, content, create_time';

        /** 查询求助信息 */
        $info = $helpModel->getFind($where, $field);

        if($info['code'] != 'ok'){
            $this->error_back($info['msg']);
        }

        $user_info = $userModel->getFind(['id' => $info['data']['user_id']], 'nickname, head_img');

        if($user_info['code'] != 'ok'){
            $this->error_back('获取信息失败，找不到求助发布者信息');
        }

        $info['data']['user_info'] = $user_info['data'];
        $imgs = $imgModel->getList(['obj_id' => $info['data']['id'], 'type' => 2], 0, 0, 0, 'img')['data'];

        $info['data']['imgs'] = array_column($imgs->toArray(), 'img');

        $this->success_back('ok', $info['data']);
    }

    /** 求助评论 */
    public function help_comment()
    {
        $data = input('');

        try{
            validate(CommentValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $commentModel = new Comment();

        $data['type'] = 1;
        $flag = $commentModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('评论成功');
    }

    /** 求助详情的评论 */
    public function help_comment_list()
    {
        $data = input('');

        try{
            validate(HelpValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new User();
        $commentModel = new Comment();

        /** 查询评论列表 */
        $where = ['obj_id' => $data['help_id'], 'type' => 1];
        $field = 'id, user_id, content, count_like, create_time';
        $list = $commentModel->getList($where, 1, $data['page'], $data['limit'], $field, 'create_time DESC');

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据');
        }

        $userModel = new User();

        foreach($list['data'] as $k => $v){
            $user_info = $userModel->getFind(['id' => $v['user_id']], 'nickname, head_img');

            if($user_info['code'] != 'ok'){
                unset($list['data'][$k]);
                continue;
            }

            $v['user_info'] = $user_info['data'];
        }

        $this->success_back('ok', $list['data']);
    }

    /** 求助评论点赞||取消点赞 */
    public function help_comment_like()
    {
        $data = input('');

        try{
            validate(CommentValidate::class)->scene('like')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $commentModel = new Comment();

        /** 查询评论的信息 */
        $comment_info = $commentModel->getFind(['id' => $data['comment_id']], 'id, user_id');

        if($comment_info['code'] != 'ok'){
            $this->error_back('点赞失败：评论不存在');
        }

        if($comment_info['data']['user_id'] == $data['user_id']){
            $this->error_back('不能给自己点赞');
        }

        $likeModel = new CommentLike();

        /** 点赞||取消点赞 */
        $where = ['user_id' => $data['user_id'], 'comment_id' => $data['comment_id']];
        $info = $likeModel->getFind($where);

        if($info['code'] != 'ok'){
            $flag  = $likeModel->add($data);
            $field = '点赞';
            $inc   = 1;
        }else{
            $flag  = $likeModel->del($where);
            $field = '取消点赞';
            $inc   = 0;
        }

        if($flag['code'] != 'ok'){
            $this->error_back($field . '失败');
        }

        /** 评论点赞量自增或自减 */
        if($inc){
            $commentModel->setIncField(['id' => $data['comment_id']], 'count_like');
        }else{
            $commentModel->setDecField(['id' => $data['comment_id']], 'count_like');
        }

        $this->success_back($field . '成功');
    }
}